<?php
class Model_Theme extends Table_Theme {
    private $currentTheme = Null;
    private $adminTheme = Null;
    private $rootDir = Null;
    // 当前主题的模板中复写的函数
    private $template = array();
    private $view = array();
    function Model_Theme($params = Null) {
        parent::__construct($params);
        $this->rootDir = FLEA::getAppInf('rootDir');
        $this->currentTheme = $this->findByField('enabled', 1);
        $this->adminTheme = $this->findByField('admin_theme', 1);
        $this->updateList();
    }
    function updateList() {
        $systemThemeDirs = FLEA::getAppInf('themeDirs');
        $themes = array();
        // 获得所有的主题名称与路径
        foreach($systemThemeDirs as $dir) {
            $results = $this->scanThemeDir($dir);
            foreach($results as $result) {
                array_push($themes, $result);
            }
        }
        $themeInDb = $this->findAll(null, null, null, array('name', 'path'));
        // index.php所在的目录
        foreach($themes as &$value) {
            // 取得相对index.php的地址
            $value['path'] = array_pop(explode($this->rootDir['absolute'], $value['path']));
            // serialize，因为array_diff不支持多维数组比较
            $value = serialize($value);
        }
        // serialize，因为array_diff不支持多维数组比较
        foreach($themeInDb as &$value) {
            $value = serialize($value);
        }
        // 需要删除的主题
        $toDelete = array_diff($themeInDb, $themes);
        // 需要添加的主题
        $toAdd = array_diff($themes, $themeInDb);
        //dump($themeInDb);dump($themes);dump($toDelete);dump($toAdd);
        if($toDelete) {
            do {
                $value = unserialize(array_pop($toDelete));
                $this->removeByConditions("path = '{$value['path']}'");
            }while($toDelete);
        }
        if ($toAdd) {
            foreach($toAdd as $value) {
                $value = unserialize($value);
                $this->create($value);
            }
        }
    }
    /**
     *
     */
    function theme() {
        $args = func_get_args();
        // 欲调用的模块名和函数名， array($moduleName, $methodName);
        // 其中methodName为去除theme前缀的方法名，如欲调用Node模块的themeNodeVew，
        // 应写为array('Node', 'nodeView');
        // 若模板中欲覆盖某theme函数应命名为templateMethodName
        $function = array_shift($args);
        $this->currentTheme = $this->findByField('enabled', 1);
        $templatePath = $this->rootDir['absolute']. $this->currentTheme['path']. '/template.php';
        if(file_exists($templatePath)) {
            require_once($templatePath);
            $templateFunction = 'template'. ucfirst($function[1]);
            if(function_exists($templateFunction)) {
                return  call_user_func_array($templateFunction, $args);
            }
        }
        $function[1] = 'theme'. ucfirst($function[1]);
        $function[0] = FLEA::getSingleton($function[0]);
        if(method_exists($function[0], $function[1])) {
            return call_user_func_array($function, $args);
        }
        
    }
    function themePage($variables) {
        extract($variables);
        $css = $this->getCss();
        require_once($this->rootDir['absolute']. $this->currentTheme['path']. '/page.tpl.php');
    }
    
    function getCss() {
        $css =  '<style type="text/css" media="all">@import "'. $this->rootDir['relative'].$this->currentTheme['path']. '/css/style.css'. '";</style>'. "\n";
        return $css;
    }
    /**
     * 查找Theme文件夹
     */
    private function scanThemeDir($dir) {
        $dirs = array();
        if(!is_dir($dir)) {
            return false;
        }
        $entries = scandir($dir);
        if(in_array('page.tpl.php', $entries)) {
            $name = array_pop(explode('/', $dir));
            $path = $dir;
            return array('name' => $name, 'path' => $path);
        } else {
            foreach($entries as $entry) {
                if($entry == '.' OR $entry == '..') {
                    continue;
                }
                $result = $this->scanThemeDir($dir. '/'. $entry);
                if($result) {
                    if(array_key_exists('name', $result)) {
                        array_push($dirs, $result);
                    } else {
                        foreach($result as $value) {
                            array_push($dirs, $value);
                        }
                    }
                }
            }
        }
        return $dirs;
    }
}
